<?php
namespace app\api\controller\v1;
use think\Db;
use think\log;
use app\service\GaodeService;
use app\service\TravelService;
use app\service\TechnLastService;
use app\service\CouponService;
use app\service\TechnService;
class Buy extends Base
{
	public function _initialize()
	{
		parent::_initialize();
		$this->IsLogin(); //验证登录
	}

	/**
	 * 获取购买订单确认信息
	 */
	public function index()
	{
		//优惠券过期处理
		CouponService::CouponUserExpireHandle();
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;
		$params['user'] = $this->user;


//
//        $params['techn_id'] = 299;
//        $params['service_arr'] = [10];
//        $params['user']['id'] = 6879;
//        $params['user']['money'] = 111;
        $is_lh = Db::name('user')->where('id',$params['user']['id'])->find();
        if($is_lh['is_lh'] != 0)
        {
            echo json_encode(['code' => -1, 'msg' => '不可下单']);
            exit();
        }

		//dump($params);
		//验证字段
		$validate = $this->validate(
			$params,
			[
				'techn_id' => 'require'
			],
			[
				'techn_id.require' => '技师信息有误'
			]
		);


		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //判断是否选择服务
        if(count($params['service_arr']) <= 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '请选择服务项目']);
            exit();
        }
		//地址数据
		$address = null;
		$address_map = [
			'user_id' => $params['user']['id'],
			'is_delete_time' => 0
		];
		//查询地址
		if(!empty($params['address_id']))
		{
			//如果地址id存在查询
			$address_map['id'] = $params['address_id'];
		}else
		{
			//查询用户默认地址
			$address_map['is_default'] = 1;
		}
		$address = Db::name('user_address')->where($address_map)->find();
		//查询技师
		$techn = Db::name('techn')->where(['id' => $params['techn_id']])->find();
		if(empty($techn))
		{
			echo json_encode(['code' => -1, 'msg' => '技师不存在']);
            exit();
		}
		//技师升级
//		TechnLastService::TechnLevelUpgradeHandle($techn['id']);

		$service_ids = trim($techn['service_ids'], ",");
		$service_ids_arr = explode(",", $service_ids);
		$service_list = [];
		foreach($params['service_arr'] as $key => $value)
		{
			//选择项目匹配技师服务项目
			if(in_array($value['id'], $service_ids_arr))
			{
				//查询服务项目
				$service_info = Db::name('service')->where(['id' => $value['id'], 'is_shelves' => 1, 'is_delete_time' => 0])->find();
				if(!empty($service_info))
				{
					//图片
					$service_info['images'] = request()->domain().$service_info['images'];
					//价格美化
					$service_info['price'] = PriceBeautify($service_info['price']);
					$service_info['original_price'] = PriceBeautify($service_info['original_price']);
					//购买数量
					$service_info['buy_number'] = $value['buy_number'];
					//购买金额
					$service_info['total_price'] = $value['buy_number']* ((float) $service_info['price']);
					//技师昵称
					$service_info['techn_nickname'] = $techn['nickname'];
					$service_list[] = $service_info;
				}
			}
		}
		// 订单总计基础信息组合
		$total_price = empty($service_list) ? 0 : array_sum(array_column($service_list, 'total_price'));
		$base = [
			// 总价
			'total_price' => $total_price,
			// 订单实际支付金额(已减去优惠金额, 已加上增加金额)
			'actual_price' => $total_price,
			// 优惠金额
			'preferential_price' => 0.00,
			// 增加金额
			'increase_price' => 0.00,
			// 默认地址
			'address' => $address,
		];
		//获取出行方式
		$travel_arr = TravelService::$travel_arr;
		$travel_id = 1;
		//出租车出行相关费用
		$taxi_travel = [];
		//距离
		$distance = 0;
		//费用
		$travel_price = 0;
		if(!empty($travel_arr[$travel_id]))
		{
			//查询技师实时数据
			$techn_last_info = Db::name('techn_last')->where(['techn_id' => $techn['id']])->find();
			//判断如果用户地址存在
			if(!empty($address) && !empty($techn_last_info))
			{
				$route_data = http_curl('https://restapi.amap.com/v3/direction/driving?origin='.$techn_last_info['lng'].','.$techn_last_info['lat'].'&destination='.$address['lng'].','.$address['lat'].'&extensions=base&output=JSON&key='.GaodeService::$web_api_key);
				$route_data = json_decode($route_data, true);
				if($route_data['status'] == 1 && $route_data['infocode'] == 10000)
				{
                    $tmp_lu = PriceNumberFormat($route_data['route']['paths'][0]['distance']/1000);
                    //更改公里为米
//                    if ($tmp_lu <0.5)
					$distance = PriceNumberFormat($route_data['route']['paths'][0]['distance']/1000); //行驶距离(米)
					//算费用
					//判断距离是否大于3公里
				// 	if($distance > $travel_arr[$travel_id]['config']['start_distance'])
				// 	{
				// 		//大于3公里
				// 		$surplus_dis = $distance-$travel_arr[$travel_id]['config']['start_distance'];
				// 		$travel_price = PriceNumberFormat((($surplus_dis*$travel_arr[$travel_id]['config']['distance_price'])+$travel_arr[$travel_id]['config']['start_price'])*2);
				// 	}else
				// 	{
				// 		//3公里内
				// 		$travel_price = $travel_arr[$travel_id]['config']['start_price']*2;
				// 	}



					$sys_chefei=db::name('chefei')->where(['proxy_id'=>0,'is_delete_time'=>0])->find();

                    $proxy_id=db::name('proxy')->where('qu',$techn_last_info['county'])->value('proxy_id');

                    if (empty($proxy_id)){
                        $proxy_id=db::name('proxy')->where('shi',$techn_last_info['city'])->value('proxy_id');
                    }

					if($proxy_id>0){
					    
					    $chefei=db::name('chefei')->where(['proxy_id'=>$proxy_id,'is_delete_time'=>0])->find();
					    
					    if(!empty($chefei)){
					        
					        $sys_chefei=$chefei;
					        
					    }

					}
					
					
					$h=date('H');
					
					
					$h1=!empty($sys_chefei['h1'])?$sys_chefei['h1']:'7';
					$h2=!empty($sys_chefei['h2'])?$sys_chefei['h2']:'21';
					
					$start_price=$sys_chefei['start_price_b'];//起步价
					$distance_price=$sys_chefei['distance_price_b'];//每公里单价
					
					if($h<$h1||$h>$h2){//晚间
					    $start_price=$sys_chefei['end_price_y'];
					    $distance_price=$sys_chefei['distance_price_y'];
					}
					
					if($distance > $sys_chefei['start_distance'])
					{
						//大于3公里
						$surplus_dis = $distance-$sys_chefei['start_distance'];
						$travel_price = PriceNumberFormat((($surplus_dis*$distance_price)+$start_price)*2);
			            $gongshi='          车费公式：('.$start_price.'+('.$distance.'-'.$sys_chefei['start_distance'].')*'.$distance_price.')*2='.$travel_price;
					}else
					{
						//3公里内
						$travel_price = $start_price*2;
			            $gongshi='          车费公式：'.$start_price.'*2='.$travel_price;
					}
                    if ($distance < 0.6) {
                        $travel_price = 0;
                    }
				}
                $taxi_travel['travel_price'] = $travel_price;
                $taxi_travel['des'] = '全程共'.$distance.'km，出租出行'.$sys_chefei['start_distance'].'公里内，起步'.$start_price.'元。里程计价：'.$distance_price.'元/公里'.$gongshi.',出行距离小于100m,不需要支付车费。';

            }else{
                $taxi_travel['travel_price'] = 0;
                $taxi_travel['des'] = '请选择地址';

            }

        }
		$base['actual_price'] += $taxi_travel['travel_price'];
		//查询优惠券
		$coupon_count = Db::name('coupon_user')->where(['user_id' => $params['user']['id'], 'is_valid' => 1, 'is_use' => 0, 'is_expire' => 0, 'where_order_price' => ['ELT', $base['total_price']]])->count();
		//如果优惠券id存在
        $coupon_name = '';
		if(!empty($params['coupon_id']))
		{
			$coupon_info = Db::name('coupon_user')->where(['id' => $params['coupon_id'], 'user_id' => $params['user']['id'], 'is_valid' => 1, 'is_use' => 0, 'is_expire' => 0, 'where_order_price' => ['ELT', $base['total_price']]])->find();
			if(!empty($coupon_info))
			{
                $coupon_name = Db::name('coupon')->where('id',$coupon_info['coupon_id'])->value('name');

				$base['actual_price'] -= $coupon_info['discount_value'];
			}
		}

		// 返回数据再次处理，防止插件处理不够完善
		$base['total_price'] = ($base['total_price'] <= 0) ? 0.00 : PriceNumberFormat($base['total_price']);
		$base['actual_price'] = ($base['actual_price'] <= 0) ? 0.00 : PriceNumberFormat($base['actual_price']);
		$base['preferential_price'] = ($base['preferential_price'] <= 0) ? 0.00 : PriceNumberFormat($base['preferential_price']);
		$base['increase_price'] = ($base['increase_price'] <= 0) ? 0.00 : PriceNumberFormat($base['increase_price']);

        //处理第一条时间自动选择

        //当前时间
        $current_time = time();
        //预约间隔时间(15分钟)
        $interval_time = $current_time+900;
        //最终预约时间
        $final_time = $interval_time;
        //技师预约时间节点
        $reservation_node = [];
        //如果技师id存在查询技师
        $techn_info = [];
        if(!empty($params['techn_id']))
        {
            $techn_info = Db::name('techn')->where(['id' => $techn['id']])->find();
            if(!empty($techn_info))
            {
                $techn_info['no_pre_hour_slot'] = !empty($techn_info['no_pre_hour_slot']) ? json_decode($techn_info['no_pre_hour_slot'], true) : [];
                //查询技师已预约的订单
                $order_list = Db::name('order')->where(['techn_id' => $techn_info['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->select();
                if(!empty($order_list))
                {
                    foreach($order_list as $key => $value)
                    {
                        if(!empty($value['pre_start_time']) && !empty($value['pre_end_time']))
                        {
                            $pre_start_time = $value['pre_start_time'];
                            $pre_end_time = $value['pre_end_time']+900;
                            for($j = $pre_start_time; $j <= $pre_end_time; $j += 1800)
                            {
                                $reservation_node[] = date('Y-m-d H:i:s', $j);
                            }
                        }
                    }
                }
            }
        }
        $list_data = [];
        $week_arr = ["周日","周一","周二","周三","周四","周五","周六"];
        //开始时间
        $start_time = strtotime(date('Y-m-d', time()));
        //结束时间
        $end_time = strtotime(date('Y-m-d', strtotime("+2 day")));

        //算出开始时间与结束时间中间间隔的时间
        $key = 0;
        for($i = $start_time; $i <= $end_time; $i += 86400)
        {
            $list_data[$key]['day'] = date('m-d', $i);
            $list_data[$key]['week'] = $week_arr[date("w", $i)];
            $time_slot = [];
            $slot_key = 0;
            //如果技师接单状态
            if(!empty($techn_info) && $techn_info['work_status'] == 1)
            {
                //开始时间段
                $start_slot = strtotime(date('Y-m-d', $i).' 00:00:00');
                //结束时间段
                $end_slot = strtotime(date('Y-m-d', $i).' 23:59:59');
                //判断是否选择接单开始时间与结束时间
                $work_start_hour = !empty($techn_info['work_start_hour']) ? strtotime(date('Y-m-d', $i).' '.$techn_info['work_start_hour'].':00') : strtotime(date('Y-m-d', $i).' 00:00:00');

                $work_end_hour = !empty($techn_info['work_end_hour']) ? strtotime(date('Y-m-d', $i).' '.$techn_info['work_end_hour'].':00') : strtotime(date('Y-m-d', $i).' 23:59:59');


                for($j = $start_slot; $j <= $end_slot; $j += 1800)
                {
                    //如果大于当前时间才显示
                    if($work_start_hour > $work_end_hour)
                    {
                        if($j >= $final_time && ($j >= $work_start_hour || $j <= $work_end_hour) && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
                        {
                            $time_slot[$slot_key]['time'] = date('H:i', $j);
                            $time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
                            $time_slot[$slot_key]['pre_date'] = $j;
                            $slot_key++;
                        }
                    }elseif ($work_start_hour < $work_end_hour) {
                        if($j >= $final_time && $j >= $work_start_hour && $j <= $work_end_hour && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
                        {
                            $time_slot[$slot_key]['time'] = date('H:i', $j);
                            $time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
                            $time_slot[$slot_key]['pre_date'] = $j;
                            $slot_key++;
                        }
                    }else
                    {
                        if($j >= $final_time && !in_array(date('Y-m-d H:i:s', $j), $techn_info['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $j), $reservation_node))
                        {
                            $time_slot[$slot_key]['time'] = date('H:i', $j);
                            $time_slot[$slot_key]['date'] = date('Y-m-d H:i:s', $j);
                            $time_slot[$slot_key]['pre_date'] = $j;
                            $slot_key++;
                        }
                    }
                    if (!empty($time_slot)){
                        break;
                    }
                }
            }
            $list_data[$key]['time_slot'] = $time_slot;
            $key++;
            break;
        }
//        $list_data[0]['time_slot']['now'] = $list_data[0]['time_slot'][0];




		// 数据返回组装
		$result['code'] = 0;
	    $result['msg'] = "请求成功";
	    $result['data'] = [
	    	'service_list' => $service_list,
	    	'taxi_travel' => $taxi_travel,
	    	'time_slot' => $list_data[0],
	    	'base' => $base,
	    	'user' => [
	    		'money' => $params['user']['money']
	    	],
	    	'coupon_count' => $coupon_count,
	    	'coupon_name' => $coupon_name,
	    	'gztext'=>file_get_contents(request()->domain().'/api/v1/webview/jyxy')
	    ];
		echo json_encode($result,256);
	}

	/**
	 * 提交订单
	 */
	public function add()
	{
		//优惠券过期处理
		CouponService::CouponUserExpireHandle();
		$result['code'] = -1;
		$result['msg'] = "非法请求";
		$params = $this->data_post;

		$params['user'] = $this->user;
		//dump($params);
		$validate = $this->validate(
			$params,
			[
				'techn_id' => 'require',
				'address_id' => 'require',
				'pre_date' => 'require',
				'payment_id' => 'require',
				'agreement' => 'require|eq:false',
			],
			[
				'techn_id.require' => '技师信息有误',
				'address_id.require' => '请选择地址',
				'pre_date.require' => '请选择预约时间',
				'payment_id.require' => '请选择支付方式',
				'agreement.require' => '请同意协议',
				'agreement.eq' => '请同意协议',
			]
		);
		if(true !== $validate)
        {
            echo json_encode(['code' => -1, 'msg' => $validate]);
            exit();
        }
        //判断是否选择服务
        if(count($params['service_arr']) <= 0)
        {
        	echo json_encode(['code' => -1, 'msg' => '服务项目有误']);
            exit();
        }
        //地址数据
        $address = Db::name('user_address')->where(['id' => $params['address_id'], 'user_id' => $params['user']['id'], 'is_delete_time' => 0])->find();
        if(empty($address))
        {
        	echo json_encode(['code' => -1, 'msg' => '地址不存在']);
            exit();
        }
        //查询技师
        $techn = Db::name('techn')->where(['id' => $params['techn_id']])->find();
        if(empty($techn))
		{
			echo json_encode(['code' => -1, 'msg' => '技师不存在']);
            exit();
		}else{
            if($techn['work_status'] == 2)
            {
                echo json_encode(['code' => -1, 'msg' => '技师休息中，请在技师服务时间内下单']);
                exit();
            }
        }


		//判断技师与用户是否为同一人
		/*if($techn['user_id'] == $params['user']['id'])
		{
			echo json_encode(['code' => -1, 'msg' => '不能预约自己的服务']);
            exit();
		}*/
		$service_ids = trim($techn['service_ids'], ",");
		$service_ids_arr = explode(",", $service_ids);
		$service_list = [];
		foreach($params['service_arr'] as $key => $value)
		{
			//选择项目匹配技师服务项目
			if(in_array($value['id'], $service_ids_arr))
			{
				//查询服务项目
				$service_info = Db::name('service')->where(['id' => $value['id'], 'is_shelves' => 1, 'is_delete_time' => 0])->find();
				if(!empty($service_info))
				{
					//购买数量
					$service_info['buy_number'] = $value['buy_number'];
					//当前购买总金额
					$service_info['total_price'] = $value['buy_number']* ((float) $service_info['price']);
					//当前购买总时长
					$service_info['total_duration'] = $value['buy_number']*$service_info['duration'];

					//打入数组
					$service_list[] = $service_info;
				}
			}
		}
		if(empty($service_list))
		{
			echo json_encode(['code' => -1, 'msg' => '服务项目不存在']);
            exit();
		}
		//dump($service_list);
		// 订单总价
		$total_price = empty($service_list) ? 0 : array_sum(array_column($service_list, 'total_price'));
		// 订单总计时长
		$total_duration = empty($service_list) ? 0 : array_sum(array_column($service_list, 'total_duration'));
		// 订单实际支付金额(已减去优惠金额, 已加上增加金额)
		$actual_price = $total_price;
		// 订单优惠金额
		$preferential_price = 0;
		//扩展展示数据
		$extension_data = [];
		//获取出行方式
		$travel_arr = TravelService::$travel_arr;
		
		$travel_id = 1;
		//出租车出行相关费用
		//距离
		$distance = 0;
		//费用
		$travel_price = 0;
		
		if(!empty($travel_arr[$travel_id]))
		{
			//查询技师实时数据
			$techn_last_info = Db::name('techn_last')->where(['techn_id' => $techn['id']])->find();
			//判断如果用户地址存在
			if(!empty($address) && !empty($techn_last_info))
			{
				$route_data = http_curl('https://restapi.amap.com/v3/direction/driving?origin='.$techn_last_info['lng'].','.$techn_last_info['lat'].'&destination='.$address['lng'].','.$address['lat'].'&extensions=base&output=JSON&key='.GaodeService::$web_api_key);
				$route_data = json_decode($route_data, true);
				if($route_data['status'] == 1 && $route_data['infocode'] == 10000)
				{
					$distance = PriceNumberFormat($route_data['route']['paths'][0]['distance']/1000); //行驶距离(米)
					//算费用
					//判断距离是否大于3公里
				// 	if($distance > $travel_arr[$travel_id]['config']['start_distance'])
				// 	{
				// 		//大于3公里
				// 		$surplus_dis = $distance-$travel_arr[$travel_id]['config']['start_distance'];
				// 		$travel_price = PriceNumberFormat((($surplus_dis*$travel_arr[$travel_id]['config']['distance_price'])+$travel_arr[$travel_id]['config']['start_price'])*2);
				// 	}else
				// 	{
				// 		//3公里内
				// 		$travel_price = $travel_arr[$travel_id]['config']['start_price']*2;
				// 	}
					
					
					//系统车费

                    $sys_chefei=db::name('chefei')->where(['proxy_id'=>0,'is_delete_time'=>0])->find();

                    $proxy_id=db::name('proxy')->where('qu',$techn_last_info['county'])->value('proxy_id');

                    if (empty($proxy_id)){
                        $proxy_id=db::name('proxy')->where('shi',$techn_last_info['city'])->value('proxy_id');
                    }


					if($proxy_id>0){
					    
					    $chefei=db::name('chefei')->where(['proxy_id'=>$proxy_id,'is_delete_time'=>0])->find();
					    
					    if(!empty($chefei)){
					        
					        $sys_chefei=$chefei;
					        
					    }
					    
					    
					}
					
					
					$h=date('H');
					
					$h1=!empty($sys_chefei['h1'])?$sys_chefei['h1']:'7';
					$h2=!empty($sys_chefei['h2'])?$sys_chefei['h2']:'21';
					
					$start_price=$sys_chefei['start_price_b'];//起步价
					$distance_price=$sys_chefei['distance_price_b'];//每公里单价
					
					if($h<$h1||$h>$h2){//晚间
					    $start_price=$sys_chefei['end_price_y'];
					    $distance_price=$sys_chefei['distance_price_y'];
					}
					
					if($distance > $sys_chefei['start_distance'])
					{
						//大于3公里
						$surplus_dis = $distance-$sys_chefei['start_distance'];
						$travel_price = PriceNumberFormat((($surplus_dis*$distance_price)+$start_price)*2);
					}else
					{
						//3公里内
						$travel_price = $start_price*2;
					}
					
				 	if($distance<0.1){
				 	    $travel_price=0;
				 	}
					
					
				}
			}
		}
		$actual_price += $travel_price;
		//如果优惠券id存在
		$coupon_info = [];
		if(!empty($params['coupon_id']))
		{
			$coupon_info = Db::name('coupon_user')->where(['id' => $params['coupon_id'], 'user_id' => $params['user']['id'], 'is_valid' => 1, 'is_use' => 0, 'is_expire' => 0, 'where_order_price' => ['ELT', $total_price]])->find();
			if(!empty($coupon_info))
			{
			    $actual_price -= $coupon_info['discount_value'];
			    $preferential_price += $coupon_info['discount_value'];
			    $extension_data[] = [
			    	'name' => '优惠券',
			    	'price' => $coupon_info['discount_value'],
			    	'type' => 0,
			    	'tips' => '-'.$coupon_info['discount_value'].'元',
			    	'business' => 'coupon',
			    	'ext' => $coupon_info
			    ];
			}
		}
		//处理服务预约开始时间date转时间戳
		$pre_start_time = strtotime($params['pre_date']);
		//处理服务预约结束时间(预约开始时间+服务时间分钟转为秒)
		$pre_end_time = $pre_start_time+($total_duration*60);
		//判断技师是否在接单状态
		if($techn['work_status'] != 1)
		{
			echo json_encode(['code' => -1, 'msg' => '技师不在工作状态']);
            exit();
		}
		//判断预约时间是否大于当前时间
		if((time()+900) >= $pre_start_time)
		{
			echo json_encode(['code' => -1, 'msg' => '超过预约时间']);
            exit();
		}
		
		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_start_time]])->find();
		
		if(!empty($times_order)){
		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
        	exit();
		}
		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_end_time],'pre_end_time'=>['>=',$pre_end_time]])->find();
		
		if(!empty($times_order)){
		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
        	exit();
		}
		
		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['<=',$pre_start_time],'pre_end_time'=>['>=',$pre_end_time]])->find();
		
		if(!empty($times_order)){
		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
        	exit();
		}
		$times_order=db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0,'pre_start_time'=>['>=',$pre_start_time],'pre_end_time'=>['<=',$pre_end_time]])->find();
		
		if(!empty($times_order)){
		    echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
        	exit();
		}
		
		$reason=db::name('refund_log')->where(['uid'=>$params['user']['id'],'day'=>date('Y-m-d')])->count();
		
 		if($reason>2 && $this->user['id'] != 115){
 		    echo json_encode(['code' => -1, 'msg' => '您当日退款已达三次，请明日再来']);
         	exit();
 		}
		
		//技师预约时间节点
        $reservation_node = [];
        //查询技师已预约的订单
        $order_list = Db::name('order')->where(['techn_id' => $techn['id'], 'status' => ['in', '0,1,2,3,4,5'], 'order_model' => 0])->select();
        if(!empty($order_list))
        {
        	foreach($order_list as $key => $value)
        	{
        		if(!empty($value['pre_start_time']) && !empty($value['pre_end_time']))
        		{
        			//处理时间节点
        			/*if($value['service_time'] > 0)
        			{
        				$new_pre_start_time = $value['service_time'];
        			    $new_pre_end_time = $value['service_time']+($value['buy_number_duration']*60)+900;
        			}else
        			{*/
        				$new_pre_start_time = $value['pre_start_time'];
        			    $new_pre_end_time = $value['pre_end_time']+900;
        			/*}*/
        			for($j = $new_pre_start_time; $j <= $new_pre_end_time; $j += 1800)
        			{
        				$reservation_node[] = date('Y-m-d H:i:s', $j);
        			}
        		}
        	}
        }
        $techn['no_pre_hour_slot'] = !empty($techn['no_pre_hour_slot']) ? json_decode($techn['no_pre_hour_slot'], true) : [];

		//判断是否在技师工作时间
		//判断是否选择接单开始时间与结束时间
		$work_start_hour = !empty($techn['work_start_hour']) ? strtotime(date('Y-m-d', $pre_start_time).' '.$techn['work_start_hour'].':00') : strtotime(date('Y-m-d', $pre_start_time).' 00:00:00');

		$work_end_hour = !empty($techn['work_end_hour']) ? strtotime(date('Y-m-d', $pre_start_time).' '.$techn['work_end_hour'].':00') : strtotime(date('Y-m-d', $pre_start_time).' 23:30:00');
		if($work_start_hour > $work_end_hour)
		{
			if(!(($pre_start_time >= $work_start_hour || $pre_start_time <= $work_end_hour) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
			{
				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
			}
		}elseif ($work_start_hour < $work_end_hour) {
			if(!($pre_start_time >= $work_start_hour && $pre_start_time <= $work_end_hour && !in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
			{
				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
			}
		}else
		{
			if(!(!in_array(date('Y-m-d H:i:s', $pre_start_time), $techn['no_pre_hour_slot']) && !in_array(date('Y-m-d H:i:s', $pre_start_time), $reservation_node)))
			{
				echo json_encode(['code' => -1, 'msg' => '不在技师工作时间内']);
            	exit();
			}
		}
		//查询是否有机构信息
		$proxy_info = Db::name('proxy')->where(['sheng' => $techn['province'], 'shi' => $techn['city'], 'is_delete_time' => 0,'type'=>2])->find();

        //永久绑定  更该数据即可使用
        $topinfo = Db::name('user')->where('id',$params['user']['id'])->find();
        if (!empty($topinfo['top_id'])){
            $topid = $topinfo['top_id'];
        }else{
            if (!empty($params['poster_id'])){
                Db::name('user')->where('id',$topinfo['id'])->update(['top_id'=>$params['poster_id']]);
                $topid = $params['poster_id'];
            }else{
                $topid = 0;
            }
        }
		// 订单主信息
		$order = [
			'order_no' => date('YmdHis').GetRandomStr(6,'int'),
			'techn_id' => $techn['id'],
			'user_id' => $params['user']['id'],
			'user_note' => isset($params['user_note']) ? str_replace(['"', "'"], '', strip_tags($params['user_note'])) : '',
			'payment_id' => $params['payment_id'],
			'extension_data' => empty($extension_data) ? '' : json_encode($extension_data, JSON_UNESCAPED_UNICODE),
			'buy_number_duration' => $total_duration,
			'pre_start_time' => $pre_start_time,
			'pre_end_time' => $pre_end_time,
			'travel_id' => $travel_id,
			'distance' => $distance,
			'preferential_price' => ($preferential_price <= 0) ? 0.00 : PriceNumberFormat($preferential_price),
			'price' => ($total_price <= 0) ? 0.00 : PriceNumberFormat($total_price),
			'travel_price' => ($travel_price < 0) ? 0.00 : PriceNumberFormat($travel_price),
			'total_price' => ($actual_price <= 0) ? 0.00 : PriceNumberFormat($actual_price),
			//'total_price' => 0.01,
			'client_type' => ApplicationClientType(),
			'proxy_id' => !empty($proxy_info) ? $proxy_info['proxy_id'] : 0,
			'sheng' => $techn['province'],
			'shi' => $techn['city'],
			'qu' => $techn['county'],
//			'poster_id' => !empty($params['poster_id'])?$params['poster_id']:0,
			'poster_id' => $topid,
			'add_time' => time(),
			'upd_time' => time()
		];
		// 开始事务
		Db::startTrans();
		// 订单添加
		$order_id = Db::name('order')->insertGetId($order);
		if($order_id <= 0)
		{
			//事务回滚
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '订单添加失败']);
            exit();
		}
		//订单详情添加
		$order_detail = [];
		foreach($service_list as $key => $value)
		{
			$order_detail[$key]['order_id'] = $order_id;
			$order_detail[$key]['service_id'] = $value['id'];
			$order_detail[$key]['title'] = $value['title'];
			$order_detail[$key]['images'] = $value['images'];
			$order_detail[$key]['original_price'] = $value['original_price'];
			$order_detail[$key]['price'] = $value['price'];
			$order_detail[$key]['duration'] = $value['duration'];
			$order_detail[$key]['buy_number'] = $value['buy_number'];
			$order_detail[$key]['add_time'] = time();
			$order_detail[$key]['upd_time'] = time();
		}
		$order_detail_count = Db::name('order_detail')->insertAll($order_detail);
		if($order_detail_count <= 0)
		{
			//事务回滚
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '订单详情添加失败']);
            exit();
		}
		//订单地址添加
		$order_address_id = Db::name('order_address')->insertGetId([
			'order_id' => $order_id,
			'address_id' => $address['id'],
			'name' => $address['name'],
			'mobile' => $address['mobile'],
			'province' => $address['province'],
			'city' => $address['city'],
			'county' => $address['county'],
			'province_name' => $address['province_name'],
			'city_name' => $address['city_name'],
			'county_name' => $address['county_name'],
			'address' => $address['address'],
			'address_des' => $address['address_des'],
			'lng' => $address['lng'],
			'lat' => $address['lat'],
			'add_time' => time(),
			'upd_time' => time()
		]);
		if($order_address_id <= 0)
		{
			//事务回滚
			Db::rollback();
			echo json_encode(['code' => -1, 'msg' => '订单地址添加失败']);
            exit();
		}
		//如果选择优惠券更改优惠券状态
		if(!empty($coupon_info))
		{
		    $coupon_data = [
		    	'is_use'       => 1,
		    	'use_order_id' => $order_id,
		    	'use_time'     => time(),
		    	'upd_time'     => time(),
		    ];
		    if(!Db::name('coupon_user')->where(['id' => $coupon_info['id']])->update($coupon_data))
		    {
		    	//事务回滚
				Db::rollback();
				echo json_encode(['code' => -1, 'msg' => '优惠券更新失败']);
	            exit();
		    }
		}
		
		TechnService::TechnPreTimey($techn['id']);
		// 提交事务
		Db::commit();
		$result['code'] = 0;
		$result['msg'] = '下单成功';
		$result['data'] = [
			'order_id' => $order_id
		];
		echo json_encode($result);
		//走队列
		
//		//创建任务： 项目命名空间\模块\文件夹\控制器@方法
//		$job = "app\service\QueuesService@order_close";
//		//延时时间
//		$delayed_second = 300;
//		$queues_data = ['id' => $order_id];
//		\think\Queue::later($delayed_second, $job, $queues_data, 'order_close');
		
	}
}